package TemplateViewHelper

import (
	"bytes"
	"embed"
	"gitee.com/david_xxy/go-helper/PathHelper"

	"html/template"
	"net/http"
	"path"
)

type TemplateView struct {
	Dir    string //模板主目录
	Suffix string //后缀 如 ".html"
}

/**
初始化
@param dir 模板主目录(建议与fs静态资源打包同一目录)
@param suffix 模板后缀
*/
func NewTemplateView(dir string, suffix string) *TemplateView {
	return &TemplateView{
		Dir:    dir,
		Suffix: suffix,
	}
}

/**
加载模板
@param asset *embed.FS 静态资源(打包)
@param write write http.ResponseWriter http对外响应
@param data interface{} 模板数据
@param tempName string 模板名称(单个)
*/
func (t *TemplateView) TempView(asset *embed.FS, write http.ResponseWriter, data interface{}, tempName string) {
	tv(t, asset, write, data, tempName)
}

/**
加载模板
多个批量解析
@param asset *embed.FS 静态资源(打包)
@param write write http.ResponseWriter http对外响应
@param data interface{} 模板数据
@param tempName tempName []string 模板名称(多个个)
*/
func (t *TemplateView) TempViewMultiple(asset *embed.FS, write http.ResponseWriter, data interface{}, tempName []string) {
	tvm(t, asset, write, data, tempName)
}

func tv(ts *TemplateView, asset *embed.FS, write http.ResponseWriter, data interface{}, tempName string) {
	var itemTempBuffer bytes.Buffer
	itemTempBuffer.WriteString(ts.Dir)
	itemTempBuffer.WriteString(PathHelper.GetPathSeparator())
	itemTempBuffer.WriteString(tempName)
	itemTempBuffer.WriteString(ts.Suffix)
	itemTemp := itemTempBuffer.String()
	itemTempBuffer.Reset()
	_, fileName := path.Split(itemTemp)

	t, errd := template.ParseFS(asset, itemTemp)
	if errd != nil {
		_, _ = write.Write([]byte(errd.Error()))
	} else {
		err := t.ExecuteTemplate(write, fileName, data)
		if err != nil {
			_, _ = write.Write([]byte(err.Error()))
		}
	}
}

func tvm(ts *TemplateView, asset *embed.FS, write http.ResponseWriter, data interface{}, tempName []string) {
	var tempPath []string
	if tempName == nil || len(tempName) == 0 {
		_, _ = write.Write([]byte("no template load"))
		return
	}

	for _, v := range tempName {
		var itemTempBuffer bytes.Buffer
		itemTempBuffer.WriteString(ts.Dir)
		itemTempBuffer.WriteString(PathHelper.GetPathSeparator())
		itemTempBuffer.WriteString(v)
		itemTempBuffer.WriteString(ts.Suffix)
		itemTemp := itemTempBuffer.String()
		itemTempBuffer.Reset()
		//_, fileName := path.Split(itemTemp)
		tempPath = append(tempPath, itemTemp)
	}
	t, errd := template.ParseFS(asset, tempPath...)
	if errd != nil {
		_, _ = write.Write([]byte(errd.Error()))
	} else {
		err := t.Execute(write, data)
		if err != nil {
			_, _ = write.Write([]byte(err.Error()))
		}
	}
}
